//
//  AudioRecorderExampleViewController.m
//  AudioRecorderExample
//

#import "AudioRecorderExampleViewController.h"

UIButton *recordButton;
UIButton *playButton;

@implementation AudioRecorderExampleViewController

- (void)record:(id)sender {
	
	if (!audioRecorder.recording) {
		audioRecorder.record;
		[recordButton setTitle:@"Stop" forState:UIControlStateNormal];
		playButton.enabled = NO;
	}
	else {
		audioRecorder.stop;
		[recordButton setTitle:@"Record" forState:UIControlStateNormal];
		playButton.enabled = YES;
	}

}

- (void)play:(id)sender {
	
	if (!audioRecorder.recording) {
		if (audioPlayer) {
			[audioPlayer release];
		}
		
		NSError *error;
		audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url
															 error:&error];
		if (error) {
			NSLog(@"An error occured: %@", error);
		}
		else {
			audioPlayer.play;
		}

	}
}

- (void)createControls {
	
	// Record 버튼
	recordButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[recordButton setFrame:CGRectMake(60, 10, 80, 34)];
	[recordButton setTitle:@"Record" forState:UIControlStateNormal];
	[recordButton addTarget:self action:@selector(record:)
		   forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:recordButton];
	
	// Play/Pause 버튼
	playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[playButton setFrame:CGRectMake(180, 10, 80, 34)];
	[playButton setTitle:@"Play" forState:UIControlStateNormal];
	[playButton addTarget:self action:@selector(play:)
		 forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:playButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
														 NSUserDomainMask, YES);
	NSString *documentsDirectoryPath = [paths objectAtIndex:0];
	NSString *filePath = [documentsDirectoryPath
						  stringByAppendingPathComponent:@"myRecording.caf"];
	NSURL *fileURL = [NSURL fileURLWithPath:filePath];
	
	NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
								   [NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
								   [NSNumber numberWithInt:16], AVEncoderBitRateKey,
								   [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
								   [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
								   nil];
	
	NSError *error = nil;
	audioRecorder = [[AVAudioRecorder alloc] initWithURL:fileURL
												settings:audioSettings
												   error:&error];
	if (error)
		NSLog(@"error: %@", error);
	else {
		[audioRecorder prepareToRecord];
		[self createControls];
	}
}

- (void)dealloc {
    [super dealloc];
}

@end
